import axios from "axios";
import { message } from "antd";

const instance = axios.create({
    baseURL: "",
    timeout: 5000,
    method: "post",
});
const token = localStorage.getItem("token");

instance.defaults.headers = {
    token: token,
};

function http(url, options) {
    options = { url, ...options };

    return new Promise((resolve, reject) => {
        instance
            .request(options)
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                message.error(err.message);
                reject(err);
            });
    });
}

/**
 * 工具方法：包装promise返回数据的格式至：[正常数据,异常数据]
 * 适用于async/await形式的写法，可以避免使用try catch处理异常返回的数据
 * @borrows https://github.com/scopsy/await-to-js
 */
function awaitTo(promise) {
    return promise
        .then((res) => {
            return [res, null];
        })
        .catch((err) => {
            return [undefined, err];
        });
}
export function fetchPost(url, options) {
    return awaitTo(http(url, options));
}

export default http;
